package com.szly.phm.common.utils;

import io.swagger.annotations.ApiModelProperty;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PagingResultUtils {


    /**
     * @currPageNo  页面传入的页号，从一开始
     * @pageSize    每页记录数
     */
    public static <T> Map<String, Object> getPagingResultMap(List<T> list, Integer pageNum, Integer pageSize) {
        Map<String, Object> retMap = new HashMap<>();

        if (list.isEmpty()) {
            retMap.put("list", Collections.emptyList());
            retMap.put("pageNum", 0);
            retMap.put("pageSize", 0);
            retMap.put("rowCount", 0);
            return retMap;
        }

        int totalRowNum = list.size();
        int totalPageNum = (totalRowNum - 1) / pageSize + 1;

        int realPageNo = pageNum;
        if (pageNum > totalPageNum) {
            realPageNo = totalPageNum;
        } else if (pageNum < 1) {
            realPageNo = 1;
        }

        int fromIdx = (realPageNo - 1) * pageSize;
        int toIdx = realPageNo * pageSize ;

        if (realPageNo == totalPageNum && totalPageNum * pageSize > totalRowNum) {
            toIdx = totalRowNum ;
        }

        List<T> result = list.subList(fromIdx, toIdx);

        retMap.put("list", result);
        retMap.put("pageNum", realPageNo);
        retMap.put("pageSize", result.size());
        retMap.put("rowCount", totalRowNum);
        return retMap;
    }
}
